package com.bilibili.org.service.impl;

import com.bilibili.basic.serivce.impl.BaseServiceImpl;
import com.bilibili.basic.util.PageList;
import com.bilibili.org.domain.Department;
import com.bilibili.org.mapper.DepartmentMapper;
import com.bilibili.org.query.DepartmentQuery;
import com.bilibili.org.service.IDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Resource
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        //如果没有选择上级部门
        if(department.getParent()==null || department.getParent().getId()==null){
            //只添加自己的id - 自增长id
            department.setDirPath("/"+department.getId());
        }else{
            //获取上级部门id
            Long parent_id = department.getParent().getId();
            //获取上级部门的dirPath
            String parent_dirPath = departmentMapper.loadById(parent_id).getDirPath();
            //组装自己的id
            department.setDirPath(parent_dirPath+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        if(department.getParent()==null || department.getParent().getId()==null){
            department.setDirPath("/"+department.getId());
        }else{
            Long parent_id = department.getParent().getId();
            String parent_dirPath = departmentMapper.loadById(parent_id).getDirPath();
            //对上级部门的处理
            // /1/47/3      47
            if(parent_dirPath.indexOf(department.getId().toString())!=-1){
                throw new RuntimeException("上级部门不能选择自己");
            }
            department.setDirPath(parent_dirPath+"/"+department.getId());
        }
        departmentMapper.update(department);
    }



    /**
     * 部门数
     */
    @Override
    public List<Department> deptTree() {
        List<Department> all = departmentMapper.loadAll();
        HashMap<Long, Department> map = new HashMap<>();
        // 循环遍历
        for (Department department : all) {
            map.put(department.getId(),department);
        }
        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : all) {
            if (department.getParent_id()==null){
                deptTree.add(department);
        }else{
                Long parent_id= department.getParent_id();
                Department parentDepartment = map.get(parent_id);
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
